package com.zqyl.docmanager.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class DocumentConverterService {

    /**
     * 将Word文档转换为Markdown
     */
    public String wordToMarkdown(byte[] wordContent) throws IOException {
        try (XWPFDocument document = new XWPFDocument(new ByteArrayInputStream(wordContent))) {
            StringBuilder markdown = new StringBuilder();
            
            // 处理段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                processParagraph(paragraph, markdown);
            }
            
            // 处理表格
            for (XWPFTable table : document.getTables()) {
                processTable(table, markdown);
            }
            
            return markdown.toString();
        }
    }

    /**
     * 将PDF文档转换为Markdown
     */
    public String pdfToMarkdown(byte[] pdfContent) throws IOException {
        try (PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfContent))) {
            PDFTextStripper stripper = new PDFTextStripper();
            String text = stripper.getText(document);
            
            // 将文本转换为Markdown格式
            return convertTextToMarkdown(text);
        }
    }

    private void processParagraph(XWPFParagraph paragraph, StringBuilder markdown) {
        String text = paragraph.getText();
        if (text == null || text.trim().isEmpty()) {
            markdown.append("\n");
            return;
        }

        // 处理标题
        if (paragraph.getStyle() != null && paragraph.getStyle().startsWith("Heading")) {
            int level = Character.getNumericValue(paragraph.getStyle().charAt("Heading".length()));
            markdown.append(StringUtils.repeat("#", level)).append(" ");
        }

        // 处理文本样式
        for (XWPFRun run : paragraph.getRuns()) {
            String runText = run.getText(0);
            if (runText == null) continue;

            if (run.isBold()) {
                markdown.append("**").append(runText).append("**");
            } else if (run.isItalic()) {
                markdown.append("*").append(runText).append("*");
            } else {
                markdown.append(runText);
            }
        }

        markdown.append("\n\n");
    }

    private void processTable(XWPFTable table, StringBuilder markdown) {
        List<Integer> columnWidths = new ArrayList<>();
        
        // 获取表格的列数
        XWPFTableRow firstRow = table.getRows().get(0);
        int columnCount = firstRow.getTableCells().size();
        
        // 初始化列宽
        for (int i = 0; i < columnCount; i++) {
            columnWidths.add(3); // 最小列宽
        }
        
        // 计算每列的最大宽度
        for (XWPFTableRow row : table.getRows()) {
            for (int i = 0; i < row.getTableCells().size(); i++) {
                String cellText = row.getCell(i).getText().trim();
                columnWidths.set(i, Math.max(columnWidths.get(i), cellText.length()));
            }
        }
        
        // 生成表格头
        for (int i = 0; i < firstRow.getTableCells().size(); i++) {
            String cellText = firstRow.getCell(i).getText().trim();
            markdown.append("| ").append(cellText)
                    .append(StringUtils.repeat(" ", columnWidths.get(i) - cellText.length()));
        }
        markdown.append("|\n");
        
        // 生成分隔行
        for (Integer width : columnWidths) {
            markdown.append("|").append(StringUtils.repeat("-", width + 2));
        }
        markdown.append("|\n");
        
        // 生成数据行
        for (int rowNum = 1; rowNum < table.getRows().size(); rowNum++) {
            XWPFTableRow row = table.getRow(rowNum);
            for (int i = 0; i < row.getTableCells().size(); i++) {
                String cellText = row.getCell(i).getText().trim();
                markdown.append("| ").append(cellText)
                        .append(StringUtils.repeat(" ", columnWidths.get(i) - cellText.length()));
            }
            markdown.append("|\n");
        }
        
        markdown.append("\n");
    }

    private String convertTextToMarkdown(String text) {
        StringBuilder markdown = new StringBuilder();
        String[] lines = text.split("\n");
        boolean inParagraph = false;
        
        for (String line : lines) {
            line = line.trim();
            
            if (line.isEmpty()) {
                if (inParagraph) {
                    markdown.append("\n\n");
                    inParagraph = false;
                }
                continue;
            }
            
            // 检测可能的标题
            if (line.matches("^\\d+(\\.\\d+)*\\s+.*")) {
                if (inParagraph) {
                    markdown.append("\n\n");
                }
                markdown.append("## ").append(line).append("\n\n");
                inParagraph = false;
            } else {
                if (!inParagraph) {
                    inParagraph = true;
                } else {
                    markdown.append(" ");
                }
                markdown.append(line);
            }
        }
        
        return markdown.toString();
    }
} 